#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include "msg_queue.h"
#include "status.h"
#include "struct.h"
#include "tools.h"

static int msgid_ctos;
static int msgid_stoc;
Msg_ctos msg_ctos;
Msg_stoc msg_stoc;

void open_acc(void)
{
	msg_ctos.m_acc.id = get_id(ID_PATH);

	char acc_path [255] = {};
	sprintf(acc_path,"%s%u",ACCOUNT_PATH,msg_ctos.m_acc.id);

	int fd = open(acc_path,O_WRONLY | O_CREAT | O_TRUNC,0644);
	if(ERROR == fd)
	{
		perror("open");
		return;
	}

	if(0 >= write(fd,&msg_ctos.m_acc,sizeof(msg_ctos.m_acc)))
	{
		perror("write");
		return;
	}

	close(fd);

	sprintf(msg_stoc.m_str,"开户成功，帐号：%d",msg_ctos.m_acc.id);
}

int main()
{
	msgid_ctos = get_ctos_msg();
	msgid_stoc = get_stoc_msg();

	while(true)
	{
		if(ERROR == msgrcv(msgid_ctos,&msg_ctos,sizeof(msg_ctos),M_OPEN,0))
		{
			perror("msgrcv");
		}

		open_acc();

		msg_stoc.m_type = msg_ctos.m_pid;

		if(ERROR == msgsnd(msgid_stoc,&msg_stoc,sizeof(msg_stoc.m_str),0))
		{
			perror("msgsnd");
		}
	}
}
